import React,{useState,useEffect} from 'react'
import { SearchBar,Modal,Toast } from 'antd-mobile'


import { reqCommunityData } from '../../api'
import { getChooseCity } from '../../utils'
import './index.scss'

const alert=Modal.alert

export default function Search(props) {
  const chooseCity=getChooseCity()

  const {history,location}=props
  const {state}=location

  const [searchText, setSearchText] = useState('')
  const [searchData, setSearchData] = useState(null)
  const [toSearch, setToSearch] = useState(false)

  const chooseCommunity=(item)=>{
    alert('提示','是否选择'+item.communityName+'的位置',[
      {text:'取消',onPress:null},
      {text:<span style={{color:'#21b97a'}}>确定</span>,onPress:()=>{
        const {path,data}=state
        if(path==='/publish'){
          data[0][1]=item.community
          data[0][2]=item.communityName
          history.replace(path,{data})
        }else{
          history.replace(path,{community:item.community,communityName:item.communityName})
        }
      }},
    ])
  }

  useEffect(()=>{
    async function getData(params){
      Toast.loading('正在加载...',0)
      let res=await reqCommunityData(params)
      setSearchData(res.body)
      setToSearch(false)
      Toast.hide()
    }
    if(searchText!==''&&toSearch)getData({id:chooseCity.id,name:searchText})
  },[searchText,searchData,toSearch,chooseCity])

  return (
    <div>
      <div className='search-navbar'>
        <SearchBar
          value={searchText}
          placeholder="请输入小区或地区"
          onSubmit={() => setToSearch(true)}
          onCancel={() => history.replace(state.path,{data:state.data})}//setSearchText('')
          showCancelButton
          onChange={val=>setSearchText(val)}
        />
      </div>
      <div className='search-list'>
        {
          searchData===null?null:searchData.map(i=>(
            <div className='item' key={i.community} onClick={()=>chooseCommunity(i)}>
              <i className='iconfont icon-房子'></i>
              <div className='content'>
                <span>{i.communityName}</span>
                <span>{i.cityName+'>'+i.areaName+'>'+i.streetName+'>'+i.communityName}</span>
              </div>
            </div>
          ))
        }
      </div>
      
    </div>
  )
}
